<?php

namespace App\Http\Controllers;

use App\Models\Message;
use App\Models\Org;
use App\Models\Project;
use App\Models\ProjectHire;
use App\Models\UserProject;
use App\Models\WechatTempMsg;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
include(dirname(__FILE__).'/../../Libs/emoji.php');

class ProjectHireController extends Controller
{
    public function index(Request $request, $project_id) {
        $projectInfo = Project::findOrFail($project_id);

        $perPage = $request->get('perPage', 10);
        $query = ProjectHire::with(['project', 'user.volunteer'])->where('project_id', '=', $project_id);

        $query->where('verify_status', '<>', '-1');
        if ($request->has('status')) {
            $query->where('verify_status', '=', $request->get('status'));
        }

        $query->orderBy('verify_status', 'asc')->orderBy('created_at');

        $asExcel = $request->get("asExcel", false);

        $info = null;
        if($asExcel){
            // 保持和分页的结构一致，设置data=>{}
            $tmp = $query->get()->toArray();
            $info = array(
                'data' => $tmp
            );
        }else {
            $info = $query->paginate($perPage)->toArray();
        }

        // 自定义信息，商品购买信息，格式化
        $paymentConfig = $projectInfo->custom_payment_config;
        $customConfig = $projectInfo->custom_config;
        if ($paymentConfig || $customConfig) {
            $extendsKey = $customConfig ? array_map(function ($item) {
                return $item->key;
            }, $customConfig) : [];
            $paymentKey = $paymentConfig ? array_map(function ($item) {
                return $item->key;
            }, $paymentConfig) : [];
            foreach ($info['data'] as &$item) {
                if (!$item) continue;
                // 处理自定义扩展信息
                $itemExtends = null; // 项目自定义的扩展信息config
                if(array_key_exists('extends', $item)
                    && ($itemExtends = $item['extends']))
                {
                    if ($itemExtends) {
                        if (gettype($itemExtends) !== 'object') {
                            try {
                                $itemExtends = json_decode($itemExtends);
                            } catch (\Exception $e) {

                            }
                        }
                    }
                }

                foreach ($extendsKey as $key) {
                    if ($itemExtends && isset($itemExtends->$key)) {
                        $item[$key] = $itemExtends->$key;
                    }
                }

                // 处理项目商品的config
                $itemPayment = null; // 项目商品的config
                if(array_key_exists('payment', $item)
                   && $itemPayment = $item['payment']
                ) {
                    ;
                    if ($itemPayment) {
                        if (gettype($itemPayment) !== 'object') {
                            try {
                                $itemPayment = json_decode($itemPayment);
                            } catch (\Exception $e) {

                            }
                        }
                    }
                }

                foreach ($paymentKey as $key) {
                    if ($itemPayment && isset($itemPayment->$key)) {
                        $item[$key] = $itemPayment->$key;
                    }
                }
//                dd(gettype($item), $item);
            }
        }


        if ($asExcel){
            return Excel::create(time(),function($excel) use ($info, $customConfig,$paymentConfig){

                $excel->sheet('volunteer', function($sheet) use ($info, $customConfig, $paymentConfig){

                    $excelLabels = array(
                        '姓名', '用户名', '性别', '联系电话', '擅长方向', '志愿时长','状态', '报名时间'
                    );
                    if ($customConfig && count($customConfig) > 0) {
                        array_map(function($cusItem)use(&$excelLabels){
                            array_push($excelLabels, $cusItem->label);
                        }, $customConfig);
                    }

                    if ($paymentConfig && count($paymentConfig) > 0) {
                        array_map(function($payItem) use(&$excelLabels){
                            array_push($excelLabels, $payItem->label);
                        }, $paymentConfig);
                    }
                    $sheet->appendRow(1, $excelLabels);


                    for ($i = 0;$i<count($info['data']);$i++){
                        $item = $info['data'][$i];
//                        print_r($tmp);
                        $excelValue = array(
                            $item['user']['volunteer']['real_name'],
                            $item['user']['username'],
                            $item['user']['volunteer']['sex'] == 2 ? '女' : ($item['user']['volunteer']['sex'] == 1 ? '男' : '-'),
                            $item['user']['volunteer']['phone'],
                            isset($item['user']['volunteer']['good_at']) ? $item['user']['volunteer']['good_at'] : '',
                            $item['reward_time'],
                            $item['verify_status'] == '0' ? '待录用' : ($item['verify_status'] == '1' ? '已录用' : ($item['verify_status'] == '2' ? '已拒绝录用 理由：'.$item['verify_msg'] : $item['verify_status'])),
                            $item['created_at']
                        );
                        if ($customConfig && count($customConfig) > 0) {
                            array_map(function($cusItem)use(&$excelValue, $item){
                                if(array_key_exists($cusItem->key, $item)){
                                    $strTmp = strval($item[$cusItem->key])." ";
                                    $strTmp = emoji_unified_to_null($strTmp);
                                    array_push($excelValue, $strTmp);
                                }
                            }, $customConfig);
                        }

                        if ($paymentConfig && count($paymentConfig) > 0) {
                            array_map(function($payItem) use(&$excelValue, $item){
                                if(array_key_exists($payItem->key, $item)){
                                    $strTmp = strval($item[$payItem->key])." ";
                                    $strTmp = emoji_unified_to_null($strTmp);
                                    array_push($excelValue, $strTmp);
                                }
                            }, $paymentConfig);
                        }
//                        Log::info(strval($excelValue));
                        $sheet->appendRow($i+2, $excelValue);
                    }
                });
            })->export('xls');
        }



        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function accept(Request $request, $project_id, $id)
    {
        $projectInfo = Project::findOrFail($project_id);
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        $user = $request->user();

        if ($projectInfo->join_people_count + count($ids) > $projectInfo->people_count) {
            throw new \Exception('本次操作会使报名人数超出设定的'.$projectInfo->people_count.'人数');
        }

        $result = ProjectHire::whereIn('id',  $ids)
            // ->where('verify_status', '=', '-1')
            ->where('project_id', '=', $project_id)
            ->where('verify_status', '<>', '1')
            ->update(['verify_status' => 1]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            $sms = new \App\Libs\Sms();
            $userProjectList = ProjectHire::with(['project.org'])->whereIn('id',  $ids)->get();
            $nodes = [];
            $orgInfo = Org::find($projectInfo->org_id);
            $scoreConf = $orgInfo->getScoreConf();
            foreach($userProjectList as $item)
            {

                $content = '您申请参加的项目《'.$item->project->name.'》已被录用，请准时参加该活动；';
                $nodes[] = array('from_user_id'=>$user->id,
                    'title' => $request->get('title', ''),
                    'to_user_id'=>$item->user_id,
                    'type' => 1,
                    'content' => $content,);
                // 发送短信
                $ret = $sms->sendTemplateSMS($item->user->phone, array($item->project->name),209754);

                //微信模版消息，申请加入项目被录取
                WechatTempMsg::add(1, ['user_project_id'=>$item->id]);

                //$item->volunteer->increment('score', $scoreConf['project_hire']);
//                Log::info('SCORE 申请被通过奖励积分 userId:'.$item->user->id.'  score:'.$scoreConf['project_hire']);
            }
            // 发送站内信
            DB::table('user_message')->insert($nodes);
            // 修改项目人数
            $node = Project::findOrFail($project_id);
            $node->fill(['join_people_count' => ProjectHire::where('project_id',  '=', $project_id)->where('verify_status', '=',  '1')->count()]);
            $node->save();

            return $this->returnJSON($ids, 0, '已成功录取');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }
    public function reject(Request $request, $project_id, $id)
    {
        Project::findOrFail($project_id);
        $this->validate($request, [
            'reason' => 'required'
        ]);
        $user = $request->user();

        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        $result = ProjectHire::whereIn('id',  $ids)
            // ->where('verify_status', '=', '-1')
            ->where('project_id', '=', $project_id)
            ->where('verify_status', '<>', '2')
            ->update([
            'verify_status' => 2,
            'verify_msg' => $request->get('reason')
        ]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            $sms = new \App\Libs\Sms();
            $userProjectList = ProjectHire::with(['project.org'])->whereIn('id',  $ids)->get();
            $nodes = [];
            foreach($userProjectList as $item)
            {
                $content = '您申请参加的项目《'.$item->project->name.'》未通过，请关注其他志愿活动；';
                $nodes[] = array('from_user_id'=>$user->id,
                    'title' => $request->get('title', ''),
                    'to_user_id'=>$item->user_id,
                    'type' => 1,
                    'content' => $content,);
                // 发送短信
                $ret = $sms->sendTemplateSMS($item->user->phone, array($item->project->name,  $request->get('reason')),209755);

                //微信模版消息，申请加入项目被录取
                WechatTempMsg::add(2, ['user_project_id'=>$item->id]);

            }
            // 发送站内信
            DB::table('user_message')->insert($nodes);

            $node = Project::findOrFail($project_id);
            $node->fill(['join_people_count' => ProjectHire::where('project_id',  '=', $project_id)->where('verify_status', '=',  '1')->count()]);
            $node->save();
            return $this->returnJSON($ids, 0, '已拒绝录取');
        } else {
            return $this->returnJSON(null, 1, "操作失败，重复操作？");
        }
    }

    public function sendMessage(Request $request, $project_id, $id) {
        Project::findOrFail($project_id);
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        $user = $request->user();
        $items = ProjectHire::whereIn('id', $ids)->get()->toArray();


        $data = array_map(function ($item) use($user, $request) {
            return array('from_user_id'=>$user->id,
                'to_user_id' => $item['user_id'],
                'title' => $request->get('title', ''),
                'type' => 1,
                'content' => $request->get('content', ''));
        }, $items);

        if (Message::insert($data)) {
            return $this->returnJSON($ids, 0, '发送成功');
        }

        return $this->returnJSON(null, 1, "操作失败");
    }

     public function getSchema(Request $request, $project_id)
     {
         $projectInfo = Project::findOrFail($project_id);
//        Log::info($projectInfo);
         $schema = [
             'type' => "wrapper",
             'className' => "b-l b-b b-r bg-white no-padder",
             'body' => [
                 'type' => "crud",
                 'bulkActions' => [
                     [
                         'label' => "录用",
                         'type' => "button",
                         'level' => "success",
                         'actionType' => "ajax",
                         'api' => 'post:/api/project/${params.id}/hire/accept/${ids}'
                     ],

                     [
                         'label' => "拒绝录用",
                         'type' => "button",
                         'level' => "danger",
                         'actionType' => "dialog",
                         'dialog' => [
                             'title' => "批量不通过",
                             'body' => [
                                 'type' => "form",
                                 'api' => 'post:/api/project/${params.id}/hire/reject/${ids}',
                                 'controls' => [
                                     [
                                         'type' => "text",
                                         'label' => "驳回理由",
                                         'name' => "reason"
                                     ]
                                 ]
                             ]
                         ]
                     ],

                     [
                         'label' => "群发消息",
                         'type' => "button",
                         'level' => "primary",
                         'actionType' => "dialog",
                         'dialog' => [
                             'title' => "批量群发消息",
                             'body' => [
                                 'type' => "form",
                                 'api' => 'post:/api/project/${params.id}/sendMessage/${ids}',
                                 'controls' => [
                                     [
                                         'type' => "textarea",
                                         'label' => false,
                                         'name' => "content"
                                     ]
                                 ]
                             ]
                         ]
                     ]
                 ],
                 'api' => '/api/project/${params.id}/hire?status=${status}&page=${page}',
                 'panelClassName' => "no-border no-shadow bg-white",
                 'toolbarInline' => true,
                 'toolbar' => [
                     'label' => "导出报名表",
                     'type' => "button",
                     'size' => "sm",
                     'actionType' => "url",
                     'className' => "btn btn-info",
                     'url' => '/api/project/${id}/hire?status=${status}&asExcel=1'
                 ],
                 'columnsTogglable' => false,
                 'filter' => [
                     'title' => "",
                     'submitText' => "",
                     'panelClassName' => 'no-border no-shadow b-b m-b-none b-light',
                     'controls' => [
                         [
                             'type' => "button-group",
                             'btnActiveClassName' => "btn-info active",
                             'value' => "",
                             'submitOnChange' => true,
                             'name' => "status",
                             'options' => [
                                 [
                                     'label' => "全部",
                                     'value' => ""
                                 ],
                                 [
                                     'label' => "报名",
                                     'value' => "0"
                                 ],
                                 [
                                     'label' => "已录用",
                                     'value' => "1"
                                 ],
                                 [
                                     'label' => "拒绝录用",
                                     'value' => "2"
                                 ]
                             ]
                         ]
                     ]
                 ],
             ]
         ];
         $columns = [
             [
                 'label' => "姓名",
                 'name' => 'user.volunteer.real_name'
             ],
             [
                 'label' => "用户名",
                 'name' => "user.username"
             ],
             [
                 'label' => "性别",
                 'name' => 'user.volunteer.sex',
                 'type' => 'map',
                 'map' => [
                     '1' => '男',
                     '2' => '女'
                 ]
             ],
             [
                 'label' => "联系电话",
                 'name' => 'user.volunteer.phone'
             ],
             [
                 'label' => "擅长方向",
                 'name' => 'user.volunteer.good_at'
             ],

             [
                 'label' => "志愿时长",
                 'name' => 'reward_time'
             ],

             [
                 'label' => "状态",
                 'name' => "verify_status",
                 'type' => "map",
                 'map' => [
                     "0" => "<span class='label label-warning'>待录用</span>",
                     "1" => "<span class='label label-success'>已录用</span>",
                     "2" => '<span class="label label-default">已拒绝录用</span> ${verify_msg}',
                     "*" => '${verify_status}'
                 ]
             ],
             [
                 'label' => "报名时间",
                 'name' => 'created_at',
                 'type' => 'tpl',
                 'tpl' => '${created_at|date:LL:YYYY-MM-DD HH:mm:ss}'
             ]
         ];
         if ($customConfig = $projectInfo->custom_config) {
             foreach ($customConfig as $item) {
//                if ($item)
                 if (!isset($item->key)) {
                     continue;
                 }
//                 dd(gettype($item), $item);
                 $key = $item->key;
                 switch ($item->type) {
                     case 5:
                         $columns[] = [
                             'name' => $key,
                             'label' => $item->label,
                             'type' => 'image',
                             'popOver' => [
                                 'title' => '',
                                 'body' => '<div class="w w-xxl"><img class="w-full" src=${' . $key . '} /></div>'
                             ]
                         ];
                         break;
//                    case 6:
//                        $columns[] = [
//                            'name' => $item->key,
//                            'label' => $item->label,
//                            'type' => 'tpl',
//                            'tpl' => '${'.$key.'}|date:LL:YYYY-MM-DD}'
//                        ];
//                        break;
//                    case 7:
//                        $column[] = [
//                            'type' => 'tpl',
//                            'tpl' => '${'.$key.'}|date:LL:YYYY-MM-DD}'
//                        ];
                     default:
                         $columns[] = [
                             'name' => $item->key,
                             'label' => $item->label,
//                             'width' => 120,
                         ];
                 }
             }
         }

         if ($paymentConfig = $projectInfo->custom_payment_config) {
             foreach ($paymentConfig as $item) {
                 if (!isset($item->key)) {
                     continue;
                 }
                $columns[] = [
                    'name' => $item->key,
                    'label' => $item->label,
                ];
             }
         }

         $schema['body']['columns'] = $columns;
         return $this->returnJSON($schema, 0, '');

     }
}
